﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LessonStudio.UI
{
    /// <summary>
    /// Interaction logic for LessonEditWnd.xaml
    /// </summary>
    public partial class LessonEditWnd : UserControl
    {
        public event Action OnOK;
        public event Action OnCancel;
        public LessonEditWnd(Models.AppSetting appSetting, Models.LessonDescription lesson)
        {
            InitializeComponent();
            _appSetting = appSetting;
            _lesson = lesson;
            InitUI();
            BindEvents();
        }

        #region 事件处理
        private void OnButtonOKClick(object sender, RoutedEventArgs e)
        {
            //创建课件:需要把文件复制过来
            try
            {
                CreateLesson();
                OnOK?.Invoke();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void OnButtonCancelClick(object sender, RoutedEventArgs e)
        {
            OnCancel?.Invoke(); 
        }

        private void OnButtonSelectImageClick(object sender, RoutedEventArgs e)
        {
            //
            var dialog = new OpenFileDialog();
            dialog.Filter = "图像文件(*.jpg;*.png)|*.jpg;*.png";
            if (dialog.ShowDialog().GetValueOrDefault())
            {
                string filePath = dialog.FileName;

                try
                {
                    _lesson.ImageFile = filePath;
                }
                catch (Exception exp)
                {
                    System.Diagnostics.Debug.WriteLine(exp);
                }
            }

        }

        private void OnButtonAddFileClick(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.Filter = "课件文件(*.pdf;*.jpg;*.png)|*.pdf;*.jpg;*.png";
            dialog.Multiselect = true;
            if (dialog.ShowDialog().GetValueOrDefault())
            {
                if(dialog.FileNames != null)
                {
                    var curOrder = GetOrder();
                    foreach (string file in dialog.FileNames)
                    {
                        var fi = new System.IO.FileInfo(file);
                        var f = new Models.LessonFile()
                        {
                            Name = fi.Name,
                            FilePath = fi.FullName,
                            Order = curOrder + 1,
                        };
                        curOrder = curOrder + 1;
                        _lessonFiles.Add(f);
                    }
                }
            }
        }

        private void OnButtonUpClick(object sender, RoutedEventArgs e)
        {
            //上移:首先需要知道自己的位置
            var btn = sender as Button;
            if (btn == null) return;
            var data = btn.DataContext as Models.LessonFile;
            if(data == null) return;
            var idx = FindIndex(data);
            if (idx < 0) return;
            if (idx == 0) return;
            //已经是最上面的，不需要移动
            var prev = idx - 1;
            var prevItem = _lessonFiles[prev];
            var curItem = _lessonFiles[idx];
            int temp = prevItem.Order;
            prevItem.Order = curItem.Order;
            curItem.Order = temp;
            _lessonFiles.RemoveAt(idx);
            _lessonFiles.Insert(prev, curItem);
        }

        private void OnButtonDownClick(object sender, RoutedEventArgs e)
        {
            //上移:首先需要知道自己的位置
            var btn = sender as Button;
            if (btn == null) return;
            var data = btn.DataContext as Models.LessonFile;
            if (data == null) return;
            var idx = FindIndex(data);
            if (idx < 0) return;
            if (idx == (_lessonFiles.Count - 1)) return;
            //已经是最下面的，不需要移动
            var next = idx + 1;
            var nextItem = _lessonFiles[next];
            var curItem = _lessonFiles[idx];
            int temp = nextItem.Order;
            nextItem.Order = curItem.Order;
            curItem.Order = temp;
            //删除后面的
            _lessonFiles.RemoveAt(next);
            _lessonFiles.Insert(idx, nextItem);
        }

        private void OnButtonDeleteClick(object sender, RoutedEventArgs e)
        {
            //删除
            var btn = sender as Button;
            if (btn == null) return;
            var data = btn.DataContext as Models.LessonFile;
            if (data == null) return;
            _lessonFiles.Remove(data);
        }

        #endregion

        #region 辅助函数
        Models.AppSetting _appSetting = null;
        Models.LessonDescription _lesson = null;
        ObservableCollection<Models.LessonFile> _lessonFiles = new ObservableCollection<Models.LessonFile>();
        void InitUI()
        {
            this.DataContext = _lesson;
            listboxFiles.ItemsSource = _lessonFiles;
        }

        void BindEvents()
        {
            btnOK.Click += OnButtonOKClick;
            btnCancel.Click += OnButtonCancelClick;
            btnSelectImage.Click += OnButtonSelectImageClick;
            btnAddFile.Click += OnButtonAddFileClick;
        }

        void CreateLesson()
        {
            //首先使用Name创建一个文件夹
            if (string.IsNullOrEmpty(_lesson.Name))
                throw new Exception("名称不能为空！");

            var lessonDir = System.IO.Path.Combine(_appSetting.LessonBaseDir, _lesson.Name);
            if (!System.IO.Directory.Exists(lessonDir))
            {
                System.IO.Directory.CreateDirectory(lessonDir);
            }
            else
            {
                throw new Exception(String.Format("在当前目录[{0}]下已经存在名称为[{1}]的课件", _appSetting.LessonBaseDir, _lesson.Name));
            }

            if (!string.IsNullOrEmpty(_lesson.ImageFile))
            {
                if(!System.IO.File.Exists(_lesson.ImageFile))
                {
                    throw new Exception("封面图片不存在");
                }

                //复制图片
                var fi = new System.IO.FileInfo(_lesson.ImageFile);
                var dstImageFile = System.IO.Path.Combine(lessonDir, fi.Name);
                if(!System.IO.File.Exists(dstImageFile))
                {
                    System.IO.File.Copy(fi.FullName, dstImageFile, false);
                }
                else
                {
                    throw new Exception(String.Format("在当前课件目录[{0}]下已经存在同名封面文件", lessonDir, fi.Name));
                }
            }

            if(_lessonFiles.Count == 0)
            {
                throw new Exception("请添加课件需要的文件");
            }

            foreach(var v in _lessonFiles)
            {
                //可能需要组合出文件路径

                //使用相对路径
                if (!System.IO.File.Exists(v.FilePath))
                {
                    throw new Exception(String.Format("文件中的{0}不存在", v.Name));
                }
            }

            //复制
            var dstDir = System.IO.Path.Combine(lessonDir, "assets");
            if (!System.IO.Directory.Exists(dstDir))
            {
                System.IO.Directory.CreateDirectory(dstDir);
            }
            if (_lesson.Files == null)
                _lesson.Files = new List<Models.LessonFile>();
            _lesson.Files.Clear();
            foreach (var v in _lessonFiles)
            {
                //可能需要组合出文件路径
                var dstfilepath = System.IO.Path.Combine(dstDir, v.Name);
                if(System.IO.File.Exists(dstfilepath))
                {
                    //文件已经存在,不处理
                    continue;
                }

                System.IO.File.Copy(v.FilePath, dstfilepath, false);
                var t = new Models.LessonFile()
                {
                    Id = v.Id,
                    FilePath = String.Format("assets/{0}", v.Name),
                    Name = v.Name,
                    Order = v.Order,
                };
                _lesson.Files.Add(t);
            }

            //创建lesson.json文件
            var lessonfilepath = System.IO.Path.Combine(lessonDir, "lesson.json");
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(_lesson);
            System.IO.File.WriteAllText(lessonfilepath, json);
        }

        int GetOrder()
        {
            if(_lesson == null || _lesson.Files == null)
                return 0;
            int max = 0;

            foreach(var v in _lesson.Files)
            {
                if(max < v.Order)
                    max = v.Order;
            }

            return max;
        }

        int FindIndex(Models.LessonFile file)
        {
            System.Diagnostics.Debug.Assert(null != file);

            if (_lessonFiles.Count == 0)
                return -1;

            int count = _lessonFiles.Count;
            for(int i=0;i<count; i++)
            {
                if (file == _lessonFiles[i])
                    return i;
            }

            return -1;
        }
        #endregion

    }
}
